package com.oj.controller;

import com.oj.util.TelnetComponent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint("/ws/websocket/{sid}")
@Component
@Slf4j
public class WebSocketServer {
    private String sid = "";
    private static Session session;
    private static TelnetComponent telnetComponent;
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

    public WebSocketServer getWebSocketServerById(String sessionId) {
        for (WebSocketServer item : webSocketSet) {
            if (item.session.getId().equals(sessionId)) {
                return item;
            }
        }
        return null;
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        log.info("new session: " + session.getId() + ", ip: " + sid);
        this.telnetComponent = new TelnetComponent(session.getId());
        this.sid = sid;
        this.session = session;
        webSocketSet.add(this);

        try {
            String[] split = sid.split(":");
            this.telnetComponent.openSession(split[0], Integer.parseInt(split[1]));
        } catch (IOException e) {
            e.printStackTrace();
            return;
        } catch (InterruptedException e) {
            e.printStackTrace();
            return;
        }

    }

    @OnClose
    public void onClose(Session session, CloseReason reason) {
        log.info("onClose sessionId " + session.getId());
        WebSocketServer webSocket = getWebSocketServerById(session.getId());
        if (webSocket == null) {
            return;
        }
        webSocketSet.remove(webSocket);
        try {
            webSocket.telnetComponent.closeSession();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        WebSocketServer webSocket = getWebSocketServerById(session.getId());
        if (webSocket == null) {
            return;
        }
        try {
            webSocket.telnetComponent.sendCommand(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.info("onError");
    }

    public static void sendInfo(String sessionId, String message) throws IOException {
        for (WebSocketServer item : webSocketSet) {
            try {
                if(sessionId == null) {
                    item.session.getBasicRemote().sendText(message);
                }else if(item.session.getId().equals(sessionId)){
                    item.session.getBasicRemote().sendText(message);
                    break;
                }
            } catch (IOException e) {
                continue;
            }
        }
    }
    public static void close(String sessionId) {
        try {
            for (WebSocketServer item : webSocketSet) {
                log.info("close sessionId " + sessionId + ", "+ item.session.getId());
                if (item.session.getId() == sessionId) {
                    item.session.close();
                    webSocketSet.remove(item);
                }
            }
        } catch (IOException e) {
        }
    }

    public static TelnetComponent getTelnetComponent() {
        return telnetComponent;
    }

    public static void setTelnetComponent(TelnetComponent telnetComponent) {
        WebSocketServer.telnetComponent = telnetComponent;
    }
}
